package com.smartwasser.yunhtgl.apphtgl.presenter;

import com.smartwasser.yunhtgl.apphtgl.utils.Logger;
import com.smartwasser.yunhtgl.apphtgl.view.ReadOfficeView;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static com.smartwasser.yunhtgl.apphtgl.network.Retrofits.base;
import static com.smartwasser.yunhtgl.apphtgl.utils.BaseUtils.writeResponseBodyToDisk;
import static com.smartwasser.yunhtgl.apphtgl.utils.TypeUtils.getPath;

public class ReadOfficePresenterImpl implements ReadOfficePresenter {
    private ReadOfficeView readOfficeView;
    private OkHttpClient okHttpClient;

    public ReadOfficePresenterImpl(ReadOfficeView readOfficeView) {
        this.readOfficeView = readOfficeView;
    }

    @Override
    public void downOffice(final String path, String urls) {

        okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(urls).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Logger.e("onFailure");
                readOfficeView.error();
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                Logger.e("onResponse = "+response.code());
                if("404".equals(String.valueOf(response.code()))){
                    Logger.e("404");
                    readOfficeView.error();
                }else {
                    Logger.e("cao");
                    new Thread() {
                        @Override
                        public void run() {
                            readOfficeView.success(writeResponseBodyToDisk(path, response.body()));
                        }
                    }.start();
                }
            }
        });
    }

    @Override
    public void getPaths(final String name) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                readOfficeView.successGetPath(getPath(name));
            }
        }.start();
    }
}